package com.geetour.columbus.common.utils;

import java.io.InputStream;
import java.io.Reader;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;

/**
 * 读取xml工具类
 *
 * @author ChenKai
 */
public class XmlReaderHelper {

    public static Document createDocument(String fileName) {
        Document document = null;
        try {
            SAXReader reader = new SAXReader();
            document = reader.read(fileName);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return document;
    }

    public static Document createDocument(Reader input) {
        Document document = null;
        try {
            SAXReader reader = new SAXReader();
            reader.setEncoding("UTF-8");
            document = reader.read(input);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return document;
    }

    public static Document createDocument(InputStream input) {
        Document document = null;
        try {
            SAXReader reader = new SAXReader();
            //          reader.setEncoding("UTF-8");
            document = reader.read(input);
        } catch (DocumentException e) {
            throw new RuntimeException(e);
        }
        return document;
    }

    public static List selectNodesByXpath(Document doc, String xpath) {
        List nodeList = null;
        if (doc == null || xpath == null || xpath.length() == 0) {
            return nodeList;
        }
        nodeList = doc.selectNodes(xpath);
        return nodeList;
    }

    public static Node selectSingleNodeByXpath(Document doc, String xpath) {
        Node node = null;
        if (doc == null || xpath == null || xpath.length() == 0) {
            return node;
        }
        node = doc.selectSingleNode(xpath);
        return node;
    }
}
